package com.library.cx.util;

import java.sql.*;

public class BaseDao {
    public Connection conn = null;
    public PreparedStatement stat = null;
    public ResultSet set=null;

    public Connection createrConn() {
       conn = null;
        //加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://1.116.221.28:3306/book?useUnicode=true&characterEncoding=utf8", "root", "ybpaeee7aiNa.");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     * @param conn
     */
    public void close(Connection conn,PreparedStatement stat,ResultSet set,ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(set!=null){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 增删改的通用方式
     * @param sql
     * @param arr
     * @return
     */
    public int executeUPdate(String sql, Object... arr){
        createrConn();
        int count=0 ;

        try {
            stat = conn.prepareStatement(sql);
            for (int a =0;a<arr.length;a++){
                stat.setObject(a+1,arr[a]);
            }
           count = stat.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
           close(conn,stat,null,null);
        }
        return count;
    }

    /**
     * 查询的通用方式
     * @param sql
     * @param arr
     * @return
     */
    public ResultSet executeQUery(String sql, Object... arr){
        createrConn();
        try {
            stat =conn.prepareStatement(sql);
            for (int i=0;i<arr.length;i++){
                stat.setObject(i+1,arr[i]);
            }
            set= stat.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return set;
    }

}
